import { ipcMain } from 'electron'
import * as cheerio from 'cheerio'
import ejs from 'ejs'
import fs from 'fs'
import pinyin from 'js-pinyin'
import prettier from 'prettier'

export const setupModaoDomToFormHandlers = () => {
  ipcMain.handle('modao-dom-to-form', (_event, richText: any) => {
    return new Promise(async (resolve) => {
      const formConfig = getFormConfig(richText)
      console.log(formConfig)
      const formTemplate = await renderForm(formConfig)
      const scriptsTemplate = await renderScripts(formConfig)
      resolve({ formTemplate, scriptsTemplate })
    })
  })
}

const renderForm = (formConfig: any) => {
  return new Promise((resolve, reject) => {
    fs.readFile('./src/main/handlers/modaoDomToForm/form.ejs', 'utf8', (err, template) => {
      if (err) {
        reject(err)
        console.error('Error reading template:', err)
        return
      }

      // 渲染模板，并传递变量
      const renderedTemplate = ejs.render(template, {
        formConfig
      })

      const formattedTemplate = prettier.format(renderedTemplate, {
        parser: 'vue',
        printWidth: 120,
        tabWidth: 4,
        useTabs: true
      })

      resolve(formattedTemplate)
    })
  })
}

const renderScripts = (formConfig: any) => {
  return new Promise((resolve, reject) => {
    fs.readFile('./src/main/handlers/modaoDomToForm/scripts.ejs', 'utf8', (err, template) => {
      if (err) {
        reject(err)
        console.error('Error reading template:', err)
        return
      }

      // 渲染模板，并传递变量
      const renderedTemplate = ejs.render(template, {
        formConfig
      })

      const formattedTemplate = prettier.format(renderedTemplate, {
        parser: 'typescript',
        printWidth: 120,
        tabWidth: 4,
        useTabs: true
      })

      resolve(formattedTemplate)
    })
  })
}

const getFormConfig = (richText) => {
  const $ = cheerio.load(richText)
  const formConfig: any = {
    fields: []
  }

  // 用于跟踪已使用的 name，避免重复
  const usedNames = new Set()

  // 需要过滤掉的字段列表
  const filterLabels = [
    '监督检查主体',
    '监督检查时间',
    '监督检查类别',
    '监督检查事项类别',
    '监督检查事项名称',
    '监督检查事项来源',
    '处理措施',
    '佐证材料',
    '备注'
  ]

  // 用于存储所有找到的字段

  // 第一步：找到所有具有特定样式的字段元素
  const allFields: any[] = []

  $('*').each((index, element) => {
    const $element = $(element)
    const style = $element.attr('style')

    // 检查样式是否匹配目标样式
    if (
      style &&
      style.includes('color: rgb(78,89,105)') &&
      style.includes('font-size: 14px') &&
      style.includes('font-family: AlibabaPuHui') &&
      style.includes('font-weight: 500') &&
      style.includes('line-height: 20px')
    ) {
      const label = $element.text().trim()
      if (label && !filterLabels.includes(label)) {
        // 检查字段元素是否在无效容器中
        let isValidField = true
        let $currentElement = $element.parent()

        // 向上遍历父级元素，检查是否在无效容器中
        while ($currentElement.length > 0) {
          const elementId = $currentElement.attr('id') || ''

          // 如果父级包含 isClipContent 或 id 为 canvas，则跳过这个字段
          if (elementId === 'canvas') {
            isValidField = false
            break
          }

          $currentElement = $currentElement.parent()
        }

        if (isValidField) {
          const $parent = $element.parent()
          const $firstChild = $parent.children().first()
          const isRequired = $firstChild.text().trim() === '*'

          // 生成唯一的 name
          let name = getPinYin(label)
          let counter = 1
          while (usedNames.has(name)) {
            name = `${getPinYin(label)}_${counter}`
            counter++
          }
          usedNames.add(name)

          // 计算字段的位置信息
          let cumulativeTop = 0
          let cumulativeLeft = 0
          let $positionElement = $element

          // 向上遍历，累积所有父级的位置信息
          while ($positionElement.length > 0) {
            const elementStyle = $positionElement.attr('style') || ''
            const topMatch = elementStyle.match(/top:\s*([\d.-]+)px/)
            const leftMatch = elementStyle.match(/left:\s*([\d.-]+)px/)

            if (topMatch) {
              cumulativeTop += parseFloat(topMatch[1])
            }
            if (leftMatch) {
              cumulativeLeft += parseFloat(leftMatch[1])
            }

            $positionElement = $positionElement.parent()
          }

          // 确定字段类型和选项
          let fieldType = 'text' // 默认类型
          let options: { label: string; value: string }[] | undefined = undefined
          let placeholder: string | undefined = undefined

          // 向上查找最近的 widget tree-node wWrap 容器
          let $containerElement = $element.parent()
          while ($containerElement.length > 0) {
            const containerClass = $containerElement.attr('class') || ''

            if (containerClass.includes('widget tree-node wWrap')) {
              // 在容器中查找子级元素类型
              const hasTextInput = $containerElement.find('.wMTextInput').length > 0
              const hasSelectionControl = $containerElement.find('.wSelectionControl').length > 0
              const hasSelect = $containerElement.find('.wMSelect').length > 0

              if (hasSelectionControl) {
                fieldType = 'radio'
                // 读取radio选项
                const editableSpans = $containerElement.find('.editable-span')
                if (editableSpans.length > 0) {
                  options = editableSpans
                    .map((index, element) => {
                      const optionText = $(element).text().trim()
                      return {
                        label: optionText,
                        value: optionText
                      }
                    })
                    .get()
                  console.log(`字段 "${label}" 找到radio选项:`, options)
                }
              } else if (hasSelect) {
                fieldType = 'select'
              } else if (hasTextInput) {
                fieldType = 'text'
                // 读取text输入框的placeholder
                const inputElement = $containerElement.find('input')
                if (inputElement.length > 0) {
                  const placeholderValue = inputElement.attr('placeholder')
                  if (placeholderValue) {
                    placeholder = placeholderValue
                    console.log(`字段 "${label}" 找到placeholder:`, placeholder)
                  }
                }
              }

              console.log(
                `字段 "${label}" 类型判断: textInput=${hasTextInput}, selectionControl=${hasSelectionControl}, select=${hasSelect}, 最终类型=${fieldType}`
              )
              break
            }

            $containerElement = $containerElement.parent()
          }

          const field: any = {
            label,
            name,
            type: fieldType,
            span: 12,
            required: isRequired,
            top: cumulativeTop,
            left: cumulativeLeft,
            visualIndex: cumulativeTop * 1000 + cumulativeLeft
          }

          // 如果有选项，添加到字段中
          if (options) {
            field.options = options
          }

          // 如果有placeholder，添加到字段中
          if (placeholder) {
            field.placeholder = placeholder
          }

          allFields.push(field)
          console.log(`找到字段: "${label}", 位置: top=${cumulativeTop}, left=${cumulativeLeft}`)
        }
      }
    }
  })

  console.log('找到字段总数:', allFields.length)

  // 第二步：根据位置信息对字段进行排序（优先 top，然后 left）
  allFields.sort((a, b) => {
    if (a.top !== b.top) {
      return a.top - b.top
    }
    return a.left - b.left
  })

  // 第三步：将排序后的字段添加到 formConfig
  allFields.forEach((field) => {
    // 移除临时的位置信息，只保留字段数据
    const { top, left, visualIndex, ...fieldData } = field
    formConfig.fields.push(fieldData)
  })

  return formConfig
}

const getPinYin = (text: string) => {
  text = text.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '')
  const str = pinyin.getCamelChars(text).toLowerCase()
  return `_temp_${str}`
}
